package com.chuanyang.driverh.mainorder;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chuanyang.driverh.R;
import com.chuanyang.driverh.RecodeState;
import com.chuanyang.driverh.base.BaseTitleActivity;
import com.chuanyang.driverh.bean.PushData;
import com.chuanyang.driverh.mainhome.GetOrderListActivity;
import com.chuanyang.driverh.mainhome.OrderDetailRceiveActivity;
import com.chuanyang.driverh.response2.ResultOrderOprate;
import com.chuanyang.driverh.responseresult.OrderDatailResult;
import com.chuanyang.driverh.responseresult.OrderDetailData;
import com.chuanyang.driverh.responseresult.Result;
import com.chuanyang.driverh.utils.ConstUtil;
import com.chuanyang.driverh.utils.DialogUtil;
import com.chuanyang.driverh.utils.LogUtils;
import com.chuanyang.driverh.utils.PrintUtil;
import com.chuanyang.driverh.utils.SharedPrefUtil;
import com.chuanyang.driverh.utils.SpeedUtil;
import com.chuanyang.driverh.utils.StringUtil;
import com.chuanyang.driverh.utils.eventbus.CloseActivityEvent;
import com.chuanyang.driverh.utils.eventbus.EventBusUtil;
import com.chuanyang.driverh.utils.eventbus.OrderFinish;
import com.chuanyang.driverh.utils.eventbus.PushDataEvent;
import com.chuanyang.driverh.utils.eventbus.RefleshFragEvent;
import com.chuanyang.driverh.utils.net.JsonGenericsSerializator;
import com.chuanyang.driverh.utils.net.MyCallback;
import com.chuanyang.driverh.utils.net.MyHttpUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;


public class ReceiveOrderActivity extends BaseTitleActivity {
    private MyCountDownTimer countDown;
    public static boolean iscount = false;
    private ImageView iv_receiveorder_delete;
    private TextView tv_addr_start;
//    private TextView tv_time_start;
    private TextView tv_addr_end;
//    private TextView tv_time_end;
    private TextView tv_weight;
    private TextView tv_goods_name;
    private TextView tv_allprice;
    private TextView tv_price;
    private ImageView iv_accept;

    private TextView tv_receive;
    private TextView tv_count_time;
    private TextView tv_delay;
    private TextView tv_abandon;

    private LinearLayout ll_lookdetail_div;
    private LinearLayout ll_graborder_countdown;
//    private TextView tv_other;
    private PushData pushData;
    private String orderId;
    private OrderDetailData orderDetail; //订单详情
    private int opreateType;

    private List<OrderDetailData.PassPointsBean> passlist;
    private OrderDetailData.PassPointsBean beginPalace;
    private OrderDetailData.PassPointsBean endPalace;

    private String content;

    private TextView tv_addr_detail_start;
    private TextView tv_addr_detail_end;
    private TextView tv_contactor_start;
    private TextView tv_phone_start;
    private TextView tv_contactor_end;
    private TextView tv_phone_end;
    private TextView tv_order_type;
    private TextView tv_sender;

    @Override
    protected int getContentResId() {
        return R.layout.order_act_graborder;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        iv_receiveorder_delete = (ImageView) findViewById(R.id.iv_receiveorder_delete);
        tv_addr_start = (TextView) findViewById(R.id.tv_addr_start);
        tv_addr_end = (TextView) findViewById(R.id.tv_addr_end);
        tv_weight = (TextView) findViewById(R.id.tv_weight);
        tv_goods_name = (TextView) findViewById(R.id.tv_goods_name);
        tv_allprice = (TextView) findViewById(R.id.tv_allprice);
        tv_price = (TextView) findViewById(R.id.tv_price);
        iv_accept = (ImageView) findViewById(R.id.iv_accept);
        tv_receive = (TextView) findViewById(R.id.tv_receive);
        tv_count_time = (TextView) findViewById(R.id.tv_count_time);
        tv_delay = (TextView) findViewById(R.id.tv_delay);
        tv_abandon = (TextView) findViewById(R.id.tv_abandon);
//        tv_other = (TextView) findViewById(R.id.tv_other);
        ll_lookdetail_div = (LinearLayout) findViewById(R.id.ll_lookdetail_div);
        ll_graborder_countdown = (LinearLayout) findViewById(R.id.ll_graborder_countdown);

        tv_addr_detail_start = (TextView) findViewById(R.id.tv_addr_detail_start);
        tv_addr_detail_end = (TextView) findViewById(R.id.tv_addr_detail_end);
        tv_contactor_start = (TextView) findViewById(R.id.tv_contactor_start);
        tv_phone_start = (TextView) findViewById(R.id.tv_phone_start);
        tv_contactor_end = (TextView) findViewById(R.id.tv_contactor_end);
        tv_phone_end = (TextView) findViewById(R.id.tv_phone_end);
        tv_order_type = (TextView) findViewById(R.id.tv_order_type);
        tv_sender = (TextView) findViewById(R.id.tv_sender);

    }

    @Override
    protected void initData() {
        hideTitleBar();
        pushData = (PushData) getIntent().getSerializableExtra("pushdata");
        orderId = pushData.getOrderId() + "";
        RecodeState.setReceiveOrderOpenning(true);
        if (getIntent().getSerializableExtra("OrderDetailData") != null) {
            orderDetail = (OrderDetailData) getIntent().getSerializableExtra("OrderDetailData");
         if(orderDetail!=null)   setOrederData(orderDetail, false);
        } else {
            getData();
        }
    }

    @Override
    protected void initListener() {
        iv_receiveorder_delete.setOnClickListener(this);
        ll_lookdetail_div.setOnClickListener(this);
        iv_accept.setOnClickListener(this);
        tv_delay.setOnClickListener(this);
        tv_abandon.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_abandon://点击放弃
                if(opreateType == 4){
                    finish();
                    return;
                }
                SpeedUtil.stopSpeaking();
                orderSheve("2");
                break;
            case R.id.tv_delay://点击搁置
                if (orderDetail != null) {
                    EventBus.getDefault().post(new OrderFinish(true));
                    orderDetail.setReceiveTime(System.currentTimeMillis());
                    if (pushData.getAppoint() != 0) {
                        orderDetail.setAppoint(pushData.getAppoint() + "");
                    }
                    orderDetail.setType(pushData.getType());
//                    SharedPrefUtil.setPreferences("SheveOrder", orderDetail);
//                    ActivityUtil.startActivity(activityContext,PendingOrderActivity.class);
                    SpeedUtil.stopSpeaking();
                    orderSheve("3");
                }
                break;
            case R.id.iv_accept://点击接受
                if (opreateType == 4) {//货主选择司机，网页发送的运输计划里的专线单
                    if (orderDetail != null && orderDetail.getOrderId() != 0) {
                        // startActivity(OrderDetailActivity.class, orderDetail.getOrderId() + "");

                        Intent intent=new Intent(activityContext,OrderDetailRceiveActivity.class);
                        intent.putExtra("data",orderDetail.getOrderId() + "");
                        intent.putExtra("type", "0");
                        startActivity(intent);

//                        startActivity(OrderDetailRceiveActivity.class, orderDetail.getOrderId() + "");

                        finish();
                    }
                } else {
                    SpeedUtil.stopSpeaking();
                        receiveOrder();
                }
                break;
            case R.id.iv_receiveorder_delete://点击关闭的X.
                SpeedUtil.stopSpeaking();
                orderSheve("3");
//                finish();
                break;
            case R.id.ll_lookdetail_div://点击上部分信息，进入订单信息页面。
                if (orderDetail != null && orderDetail.getOrderId() != 0) {
                    Intent intent=new Intent(activityContext,OrderDetailRceiveActivity.class);
                    intent.putExtra("data",orderDetail.getOrderId() + "");
                    intent.putExtra("type","3");
                    startActivity(intent);
                    finish();
                }
                break;
        }
    }

    //获取推送来的订单信息
    private void getData() {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", pushData.getOrderId() + "");
        MyHttpUtil.selectOrderMsgById(activityContext,params, new MyCallback<OrderDatailResult>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(OrderDatailResult result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    try {
                        orderDetail = result.getData();
                        setOrederData(result.getData(), true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }

            }
        });
    }


//订单搁置
    private void orderSheve(String oprateType) {//操作类型（1：接单，2：拒绝，3：搁置）
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,String> params=new HashMap<String, String>();
        params.put("driverId", SharedPrefUtil.getUserId());
        params.put("orderId", pushData.getOrderId() + "");
        params.put("operate", oprateType);
        params.put("type",  pushData.getType() + "");//类型（1：个人，2：车队）
        MyHttpUtil.orderShelve(activityContext,params, new MyCallback<ResultOrderOprate>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(ResultOrderOprate result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    if (result.getMsg()!=null){
                        PrintUtil.toast(activityContext,result.getMsg());
                    }else{
                        PrintUtil.toast(activityContext,"操作成功");
                    }
                    EventBusUtil.postEvent(new RefleshFragEvent(1));
                    finish();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                }
            }
        });


    }



    /**
     * 接单操作
     */
    private void receiveOrder() {
        DialogUtil.showLoadingDialog(activityContext,"加载中...");
        Map<String,Object> params=new HashMap<String, Object>();
        params.put("orderId", orderId);
        params.put("driverId",SharedPrefUtil.getUserId());
        params.put("type", pushData.getType()+"");
        if (pushData.getAppoint() != 0) {
            params.put("appoint", pushData.getAppoint() + "");
        }else{
            params.put("appoint", "1");
        }
        if (orderDetail!=null) {
            params.put("orderType", orderDetail.getOrder_type() + "");
            params.put("amount", orderDetail.getOrder_Amount() + "");
        }
        MyHttpUtil.receiveOrder(activityContext,params, new MyCallback<Result>(activityContext,new JsonGenericsSerializator()) {
            @Override
            public void onFail(Call call, Exception e, int id) {
                e.printStackTrace();
                PrintUtil.toast(activityContext, "网络异常，请稍后再试");
            }
            @Override
            public void onSuccess(Result result, int id) {
                if (result.getCode() == ConstUtil.OK) {
                    PrintUtil.toast(ReceiveOrderActivity.this, "抢单成功");
                    Intent intent = new Intent(ReceiveOrderActivity.this, GetOrderListActivity.class);
                    startActivity(intent);
                    EventBusUtil.postEvent(new RefleshFragEvent(1));
                    finish();
                }else{
                    PrintUtil.toast(activityContext,result.getMsg());
                    finish();
                }
            }
        });
    }

    private void setOrederData(OrderDetailData data, boolean invoce) {
        //获取操作的类型   (此处没有竞价订单) pushData   "2"匹配订单，显示抢单，可以搁置，可以放弃      "3"专线订单，不显示搁置和倒计时,可以拒绝但是后台无接口
        //"4"分配订单  不能拒绝

        //匹配单和app端的指定单，推送给个人为1，车队为2
        //网页发送的指定单为3
        //货主选择司机4

       //pushData 推送给个人为1，车队为2,运输计划里的专线单为3
        if (pushData.getType() != 0 && pushData.getType() == 3) {
            opreateType = 4;
        } else {
            opreateType = data.getOrder_type();
        }
        tv_order_type.setText("");

        if (opreateType == 4) {
            if(data.getFleetId()!=0)     {
                tv_order_type.setBackgroundResource(R.mipmap.order_special_t);
            }else {
                tv_order_type.setBackgroundResource(R.mipmap.order_special_t);
            }
            tv_receive.setText("阅");
            tv_delay.setVisibility(View.GONE);
            tv_abandon.setVisibility(View.GONE);
            ll_graborder_countdown.setVisibility(View.GONE);
        }else if(data.getOrder_type()==3){//普通专线单
            if(data.getFleetId()!=0) {
                tv_order_type.setBackgroundResource(R.mipmap.order_special_t);
            } else {
                tv_order_type.setBackgroundResource(R.mipmap.order_special_p);
            }
            //如果是专线订单，则不显示搁置按钮
            //专线单显示搁置，
            tv_receive.setText("接");
            tv_delay.setVisibility(View.VISIBLE);
            ll_graborder_countdown.setVisibility(View.GONE);
        }else if(data.getOrder_type()==2 ){//匹配单
            tv_receive.setText("抢");
            if(data.getFleetId()!=0) {
                tv_order_type.setBackgroundResource(R.mipmap.order_match_t);
            } else {
                tv_order_type.setBackgroundResource(R.mipmap.order_match_p);
            }
            tv_delay.setVisibility(View.VISIBLE);
            ll_graborder_countdown.setVisibility(View.VISIBLE);
            tv_abandon.setVisibility(View.VISIBLE);
            reSetView();//只有匹配订单 才需要显示倒计时和进度条
        }





        /*if (opreateType == 2) {
            if(data.getFleetId()!=0) {
                tv_other.setText("匹配 (团队)");
                tv_order_type.setBackgroundResource(R.mipmap.order_match_t);
            } else {
                tv_other.setText("匹配 (个人)");
                tv_order_type.setBackgroundResource(R.mipmap.order_match_p);
            }
            tv_delay.setVisibility(View.VISIBLE);
            ll_graborder_countdown.setVisibility(View.VISIBLE);
            tv_abandon.setVisibility(View.VISIBLE);
            reSetView();//只有匹配订单 才需要显示倒计时和进度条
        } else if (opreateType == 4) {
            if(data.getFleetId()!=0)     {
                tv_other.setText("分配 (团队)");
                tv_order_type.setBackgroundResource(R.mipmap.order_special_t);
            }else {
                tv_other.setText("分配 (个人)");
                tv_order_type.setBackgroundResource(R.mipmap.order_special_t);
            }
            tv_delay.setVisibility(View.GONE);
            tv_abandon.setVisibility(View.GONE);
            ll_graborder_countdown.setVisibility(View.GONE);
        } else {
            if(data.getFleetId()!=0) {
                tv_other.setText("专线 (团队)");
                tv_order_type.setBackgroundResource(R.mipmap.order_special_t);
            } else {
                tv_other.setText("专线 (个人)");
                tv_order_type.setBackgroundResource(R.mipmap.order_special_p);
            }
            //如果是专线订单，则不显示搁置按钮
            //专线单显示搁置，
            tv_delay.setVisibility(View.VISIBLE);
            ll_graborder_countdown.setVisibility(View.GONE);
        }*/

        if (passlist == null) {
            passlist = new ArrayList();
        }
        for (OrderDetailData.PassPointsBean bean : data.getPassPoints()) {
            if (bean.getPointType().equals("s")) {
                beginPalace = bean;
            } else if (bean.getPointType().equals("e")) {
                endPalace = bean;
            } else {
                passlist.add(bean);
            }
        }
        setGoodName(tv_goods_name,data.getGoodsName());
        tv_addr_start.setText(beginPalace.getCity()+" "+beginPalace.getRegions());
        tv_addr_end.setText( endPalace.getAddress()+" "+endPalace.getRegions());
        tv_addr_detail_start.setText(beginPalace.getAddress());
        tv_addr_detail_end.setText( endPalace.getAddress());



        tv_contactor_start.setText( beginPalace.getContactPerson());
        tv_contactor_end.setText( endPalace.getContactPerson());
        tv_phone_start.setText( beginPalace.getContactPhone());
        tv_phone_end.setText( endPalace.getContactPhone());


//        tv_order_type.setText( endPalace.getContactPhone());
//
        tv_sender.setText(data.getUsername());



        tv_weight.setText(data.getGoodsSumWeight()+"");
        tv_allprice.setText(data.getOrder_Amount() + data.getUnit());
        tv_price.setText(data.getPrice()+"");

        if (invoce) {
            invoceOrderContent(beginPalace, endPalace);
        }
    }
    /**
     * 播报订单内容
     */
    private void invoceOrderContent(OrderDetailData.PassPointsBean beginPalace, OrderDetailData.PassPointsBean endPalace) {
        content = "";
        content = "您有新的订单从" + beginPalace.getProvince() + beginPalace.getCity() + beginPalace.getRegions()
                + "到" + endPalace.getProvince() + endPalace.getCity() + endPalace.getRegions() + "请您接单";
        SpeedUtil.broadcastOrder(this, content);
    }
    private void setGoodName(TextView view, List<String> goodname) {
        String name = StringUtil.getString(goodname);
        view.setText(name);
    }

    class MyCountDownTimer extends CountDownTimer {
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        @Override
        public void onFinish() {
            super.cancel();
//            finish();
            orderSheve("2");
        }

        @Override
        public void onTick(long millisUntilFinished) {
//            tv_count_time.setText((millisUntilFinished / 1000)+"");
            String hour="";
            String min="";

            if(millisUntilFinished / 1000/60/60>1){
                hour=millisUntilFinished / 1000/60/60+"时";
            }
            min=(millisUntilFinished /1000/60%60)+"分";
            tv_count_time.setText(hour+min);
        }
    }
    private void startCountdown() {
        countDown = new MyCountDownTimer(60*1000*60*12, 1000);
        countDown.start();
        iscount = true;
    }

    @Override
    public void finish() {
        super.finish();
        if (countDown != null) countDown.cancel();
    }
    @Override
    protected void onDestroy() {
        if (countDown != null) {
            iscount = false;
            countDown.cancel();
            countDown = null;
        }
        //记录一下当前页面也关闭，此时该页面可以打开
        RecodeState.setReceiveOrderOpenning(false);
        LogUtils.e("ReceiveActivity", "destory");
        super.onDestroy();
    }


    private void reSetView() {
        if (countDown != null) {
            iscount = false;
            countDown.cancel();
            countDown = null;
        }
        startCountdown();
    }
    /**
     * 通知刷新数据
     *
     * @param event
     */
    public void onEventMainThread(PushDataEvent event) {
        if (event != null) {
            pushData = event.getPushdata();
            reSetView();
            getData();
            LogUtils.e("ReceiveActivity", "PushDataEvent-------");
        }
    }
    public void onEventMainThread(CloseActivityEvent event) {
        if (event != null && event.getIndex()==1) {
            finish();
        }
    }
}
